const mysql = require('mysql');
const config = require('../config');

class Mysql {
    constructor () {
        this.connection = mysql.createConnection(config.mysqlConfig);
        this.connection.connect();
    }

    /**
     * 
     * @param {*} params  
     * {
     *   sql: '执行查询数据库的语句 SELECT * FROM goods WHERE goods_id = ?',
     *   value: '执行查询数据库的语句 需要的数值 11'  [11]
     * }
     * @returns 
     */
    query(params) {
        return new Promise((resolve, reject) => {
            this.connection.query(params.sql, params.value, (error, results, fields) => {
                if (error) {
                    resolve(this.error(error.message, 600))
                } else {
                    resolve(this.success(results))
                }
            })
        })
        
    }

    success(data = [], message = "请求成功") {
        config.ResponseResult.code = 200
        config.ResponseResult.message = message
        config.ResponseResult.data = data
        return config.ResponseResult
    }

    error(message = "", code = "", data = []) {
        config.ResponseResult.code = code
        config.ResponseResult.message = message
        config.ResponseResult.data = data
        return config.ResponseResult
    }


}

module.exports = new Mysql()